package com.framework.oauthclient.config;

import cn.hutool.core.util.ObjectUtil;
import com.framework.common.exception.BusinessException;
import com.framework.common.util.RedisUtil;
import com.framework.common.util.StringUtils;
import com.framework.oauthclient.ext.ClientBearerTokenAuthenticationFilter;
import com.framework.oauthclient.service.OauthAuthenticationEntryPoint;
import com.framework.oauthclient.vo.ClientProperties;
import com.framework.oauthclient.vo.OAuthExcludeProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2ClientProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProvider;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.DefaultOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.web.OAuth2AuthorizedClientRepository;
import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.springframework.security.config.Customizer.withDefaults;

@EnableWebSecurity
@Configuration
@RefreshScope
public class OAuth2ClientConfig {
    @Autowired
    private OAuth2ClientProperties oAuth2ClientProperties;
    @Autowired
    public OAuthExcludeProperties properties;
    @Autowired
    RedisUtil redisUtil;

    @Bean
    public SecurityFilterChain configure(HttpSecurity http) throws Exception {
        ClientBearerTokenAuthenticationFilter filter = new ClientBearerTokenAuthenticationFilter();
        List<String> exclude = properties.getExclude();
        if (ObjectUtil.isEmpty(exclude)) {
            exclude = new ArrayList<>();
        }
        exclude.add("/");
        exclude.add("/**/favicon.*");
        exclude.add("/**/actuator/**");
        exclude.add("/**/**test");
        exclude.add("/qrcode/**");
        exclude.add("/login/**");
        exclude.add("/sso/**");
        exclude.add("/register/**");
        exclude.add("/dict/**");
        exclude.add("/v2/**");
        exclude.add("/webjars/**");
        exclude.add("/*.html**");
        exclude.add("/swagger**");
        exclude.add("/**/*.ico");
        exclude.add("/**/*.png");
        exclude.add("/**/*.css");
        exclude.add("/**/*.js");
        exclude.add("/**/*.json");
        String[] arr = new String[exclude.size()];
        exclude.toArray(arr);
        http.authorizeRequests()
                .antMatchers(arr)
                .permitAll()
                .and()
                .csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint(new OauthAuthenticationEntryPoint())
                .and()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .oauth2Client(withDefaults())
                .addFilterBefore(filter, FilterSecurityInterceptor.class);
        SecurityFilterChain filterChain = http.build();

        // 设置SecurityMetadataSource值， 用来过滤不拦截的url
        FilterSecurityInterceptor interceptor = (FilterSecurityInterceptor) filterChain
                .getFilters()
                .stream()
                .filter(it -> it instanceof FilterSecurityInterceptor)
                .findAny()
                .get();

        filter.setSecurityMetadataSource(interceptor.getSecurityMetadataSource());
        filter.setAccessDecisionManager(interceptor.getAccessDecisionManager());

        return filterChain;
    }

    @Bean
    public WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
        ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client =
                new ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager);
        return WebClient.builder()
                .apply(oauth2Client.oauth2Configuration())
                .build();
    }

    @Bean
    public OAuth2AuthorizedClientManager authorizedClientManager(
            ClientRegistrationRepository clientRegistrationRepository,
            OAuth2AuthorizedClientRepository authorizedClientRepository) {
        OAuth2AuthorizedClientProvider authorizedClientProvider =
                OAuth2AuthorizedClientProviderBuilder.builder()
                        .authorizationCode()
                        .refreshToken()
                        .build();
        DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
                clientRegistrationRepository, authorizedClientRepository);
        authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

        return authorizedClientManager;
    }

    @Bean
    public ClientProperties getClientProperties() {
        ClientProperties properties = new ClientProperties();
        Map<String, OAuth2ClientProperties.Registration> registration = oAuth2ClientProperties.getRegistration();
        Map<String, OAuth2ClientProperties.Provider> provider = oAuth2ClientProperties.getProvider();
        if (StringUtils.isEmpty(registration)) {
            throw new BusinessException("请配置：security.oauth2.client.registration");
        }
        if (StringUtils.isEmpty(provider)) {
            throw new BusinessException("请配置：security.oauth2.client.provider");
        }
        registration.forEach((k, v) -> {
            properties.setClientId(v.getClientId());
            properties.setClientSecret(v.getClientSecret());
            properties.setGrantType(v.getAuthorizationGrantType());
            properties.setScope(v.getScope());
        });
        provider.forEach((k, v) -> {
            properties.setTokenUri(v.getTokenUri());
            properties.setUserInfoUri(v.getUserInfoUri());
        });

        return properties;
    }

}
